'''
Created on 2021-10-17
@author:xianye
'''

import pandas as pd
import sdk_umeng
import userinfo
import time
import os
from datetime import date, timedelta

# check data,if no,create
try:
    file = os.listdir('./data/')
except:
    os.mkdir('data')


yesterday = date.today() - timedelta(1)

if __name__ == '__main__':
    # 1,login
    auth_token = sdk_umeng.authorize(userinfo.umeng)
    # 2,appkey
    apps = sdk_umeng.apps(auth_token)
    appkeys = []
    for appkeys in apps:
        appkeys['appkey']
        # 3,group id
        group_list = sdk_umeng.group_list(appkeys['appkey'], auth_token, start_date=yesterday,
                                         end_date=yesterday).json()
        # print(group_list)
        for i in group_list:
            # print(i)
            event_info = sdk_umeng.event_list(appkeys['appkey'], auth_token, start_date=yesterday,
                                             end_date=yesterday, group_id=i['group_id']).json()
            try:
                for event_list in event_info:
                    print(event_list)
                    event_data = sdk_umeng.parameter_list(appkeys['appkey'], auth_token, start_date=yesterday,
                                                         end_date=yesterday, event_id=event_list['event_id']).json()
                    # print(event_data)
                    df = pd.DataFrame(event_data)
                    df.to_excel(
                        './data/{}-{}-{}-{}.xlsx'.format(yesterday, appkeys['name'], i['display_name'],
                                                                      event_list['name']), index=False)
                    # print(df.head())
                    time.sleep(2)
            except Exception as e:
                print(e)
